﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.UserInfo;
import com.kuanter.kuanterauto.main.HomeActivityGroup;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.umeng.analytics.MobclickAgent;

public class LoginActivity extends WuyangBaseActivity {
	private Button login_btn;
	private Intent intent = new Intent();
	private View activate_card_goto;
	private TextView find_password_btn;
	private EditText account_number_et;
	private String account_number;
	private EditText password_et;
	private String password;
	private DataLoader dataLoader;
	private UserInfo userInfo;
	Handler handler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				// {"status":false,"errorMsg":null}
				// {"status":true,"userInfo":{"id":82739,"mobileNumber":"18638551072","userEmail":"hncaihongyu@163.com","userRealName":"蔡红玉"}}
//				String result = msg.getData().getString("result");
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
															// 字段值是否为false
							com.alibaba.fastjson.JSONObject jsonObjectResult= JSON.parseObject(result);
							String JsonStringUserInfo = jsonObjectResult.getString("userInfo");
							userInfo = JSON.parseObject(JsonStringUserInfo, UserInfo.class) ;
							//记录登录状态
							ObjectCache.set("userInfo", userInfo);
							
							// 保存用户信息到本地
							saveUserInfo();
							finishProgress();
//							LoginActivity.this.finish();
//							startMyActivity(LoginActivity.this, VipCenterActivity.class);
							Intent intent = new Intent(startAction);
							sendBroadcast(intent);
							m.hideSoftInputFromWindow(account_number_et.getWindowToken(), 0);
							m.hideSoftInputFromWindow(password_et.getWindowToken(), 0);
							
							//
							finish();
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast(StringUtil.geterrorMsg(result));
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("登录失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	private HttpClient httpClient;
	
	public static String startAction = "";
	InputMethodManager m = null;
	private DataReceiver dataReceiver = null;
	private TextView back_tv;
	
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.userlogin) ;
		startAction = getIntent().getAction();
		
		dataLoader = new DataLoader(this);
		
		m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//		m.toggleSoftInput(InputMethodManager.SHOW_FORCED,    //去掉输入框，加上这有点卡顿
//				InputMethodManager.HIDE_IMPLICIT_ONLY);
		// 注册广播
		register_Receiver();
		
		this.initBodyControlView();
		this.registerListener();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login_btn:
			this.getControlViewText();
			if ("".equals(account_number)|| account_number.length() <=0||account_number.length() >= 12) {
				showToast("请输入正确的账号");
				break;
			} else if ("".equals(password)) {
				showToast("请输入密码");
				break;
			}/* else if (!isPhoneNum(account_number)){
				showToast("请输入正确的账号");
				break;
			}*//*else if(password.length()!=6){
				showToast("请输入六位长度密码");
				break;
			}*/else{
				//联网将账户登录信息提交
				if (CheckNetworkState()) {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("userInfo.mobileNumber",
						account_number));
					params.add(new BasicNameValuePair("userInfo.userPassword",
						password));
					params.add(new BasicNameValuePair("cardNumber",
							account_number));
					dataLoader.DisplayData(MainConstants.HOST_test+HttpConfigAPI.LOGIN, params , handler, "", false);
					showProgress("登录中...");
				}
				
			}
			break;
		case R.id.activate_card_goto:
			intent.setClass(this, ActivateCardActivity.class);
			this.startActivity(intent);
			break;
		case R.id.find_password_btn:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("宽途客服热线");
			builder.setMessage("4006666377");
			builder.setPositiveButton("呼叫",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0,
								int arg1) {
							call("4006666377");
						}
					});

			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface arg0,
								int arg1) {
						}
					});

			builder.create().show();
			break;
		case R.id.back_tv:
			m.hideSoftInputFromWindow(account_number_et.getWindowToken(), 0);
			m.hideSoftInputFromWindow(password_et.getWindowToken(), 0);
			HomeActivityGroup.backAction = MainConstants.BACK_ACTION;
			if (startAction.equals(MainConstants.SZ_ACTION)) {
				HomeActivityGroup.backAction = MainConstants.SZ_ACTION;
				finish();
			} else {
				HomeActivityGroup.backAction = MainConstants.BACK_ACTION;
				qBackToActivity(HomeActivityGroup.class, null);
				startActivity_anim(11);
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void initBodyControlView() {
		// TODO Auto-generated method stub
		login_btn = (Button)this.findViewById(R.id.login_btn);
		activate_card_goto = this.findViewById(R.id.activate_card_goto);
		find_password_btn = (TextView)this.findViewById(R.id.find_password_btn);
		account_number_et = (EditText)this.findViewById(R.id.account_number);
		password_et = (EditText)this.findViewById(R.id.password_et);
		password_et.setTransformationMethod(PasswordTransformationMethod.getInstance());
//		password_et.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(6) });
//		password_et.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
		back_tv = (TextView)this.findViewById(R.id.back_tv);
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void registerListener() {
		// TODO Auto-generated method stub
		login_btn.setOnClickListener(this);
		activate_card_goto.setOnClickListener(this);
		find_password_btn.setOnClickListener(this);
		back_tv.setOnClickListener(this);
	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub
		account_number = account_number_et.getText().toString();
		password = password_et.getText().toString();
	}
	
	private void saveUserInfo() {
		// 将个人信息保存至本地
		SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("id", userInfo.getId());
		editor.putString("mobileNumber", userInfo.getMobileNumber());
		editor.putString("userEmail", userInfo.getUserEmail());
		editor.putString("userRealName", userInfo.getUserRealName());
		editor.putString("address", userInfo.getAddress());
		editor.putString("password", password);
		editor.commit();
	}
	
	private void register_Receiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(startAction);
		dataReceiver = new DataReceiver();
		registerReceiver(dataReceiver, filter);
	}
	
	class DataReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(MainConstants.CX_ACTION)) {
				startActivity(intent);
				startActivity_anim(11);
			} else if(intent.getAction().equals(MainConstants.NS_ACTION)) {
				startActivity(intent);
				startActivity_anim(11);
			} else if(intent.getAction().equals(MainConstants.LC_ACTION)) {
				startActivity(intent);
				startActivity_anim(11);
			}  else if(intent.getAction().equals(MainConstants.CZ_ACTION)) {
				startActivity(intent);
				startActivity_anim(11);
			} else if (intent.getAction().equals(MainConstants.HY_ACTION)) {
				// stopService();
				HomeActivityGroup.backAction = MainConstants.HY_ACTION;
				Intent i = new Intent(MainConstants.Data_ACTION);
				// i.putExtras(intent.getExtras());
				sendBroadcast(i);
				qBackToActivity(HomeActivityGroup.class, null);
				startActivity_anim(11);

			} else if (intent.getAction().equals(MainConstants.SZ_ACTION)) {
				HomeActivityGroup.backAction = MainConstants.SZ_ACTION;
				Intent i = new Intent(MainConstants.Data_ACTION);
				// i.putExtras(intent.getExtras());
				sendBroadcast(i);
				qBackToActivity(HomeActivityGroup.class, null);
			}
		}

	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			m.hideSoftInputFromWindow(account_number_et.getWindowToken(), 0);
			m.hideSoftInputFromWindow(password_et.getWindowToken(), 0);
			HomeActivityGroup.backAction = MainConstants.BACK_ACTION;  
			if (startAction.equals(MainConstants.SZ_ACTION)) {
				HomeActivityGroup.backAction = MainConstants.SZ_ACTION;
				finish();
			} else {
				HomeActivityGroup.backAction = MainConstants.BACK_ACTION;	
				qBackToActivity(HomeActivityGroup.class, null);
				startActivity_anim(11);
			}
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		if (dataReceiver != null) {
			unregisterReceiver(dataReceiver);
			dataReceiver = null;
		}

		// dataLoader.shutDown();
		m.hideSoftInputFromWindow(account_number_et.getWindowToken(), 0);
		m.hideSoftInputFromWindow(password_et.getWindowToken(), 0);
		super.onDestroy();
	}
	
	
}
